package org.atf.dp.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.atf.model.entity.DpService;

public class SendSomaCommand {
	//Code to Allow Opening insecure HTTPS Connection
	//Allowing all DataPower XML Management Interface Cert to create Connection without it's validation
	static Integer CONN_TIMEOUT=1000;
	private  static Logger  logger = Logger.getLogger(SendSomaCommand.class);
	static{
		try{
			TrustManager[] trustAllCerts = { new X509TrustManager() {

				
				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				
				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}
				
			}};
			SSLContext sc = SSLContext.getInstance("SSL");
			HostnameVerifier hv = new HostnameVerifier() {
				

				
				public boolean verify(String arg0, SSLSession arg1) {
					// TODO Auto-generated method stub
					return true;
				}
			};
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(hv);
		}catch(Exception exception){
			logger.error(exception);
			
		}
	}
	public static String sendRequest(DpService dpService){
		String output = "";
		String urlStr      = dpService.getUrl();
		String xmlFile2Send = dpService.getPayload();
		// Create the connection where we're going to send the file.
		logger.debug(dpService.toString());
		
		try {
			URL url = new URL(urlStr);
			URLConnection connection = url.openConnection();
			HttpURLConnection httpConn= null;
			if(url.getProtocol().equalsIgnoreCase("https")){	
				httpConn = (HttpsURLConnection) url.openConnection();
			}else{
				httpConn = (HttpURLConnection) url.openConnection();
			}
			if( httpConn != null){
				httpConn.setConnectTimeout(CONN_TIMEOUT);
				String SOAPAction = dpService.getSoapAction();
				String soapRequest = xmlFile2Send.toString();
				//Convert into bytes
				byte[] b = soapRequest.getBytes();
				httpConn.setRequestProperty( "Content-Length",String.valueOf( b.length ) );
				if(dpService.getContentType() != null && 
						!dpService.getContentType().equalsIgnoreCase("")){
					httpConn.setRequestProperty("Content-Type", dpService.getContentType());
				}else{
					httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");

				}
				httpConn.setRequestProperty("SOAPAction",SOAPAction);
				
				//Create UsernamePassword 
				//To Base64 decoding, Apache common-codec is used.
				
				if (dpService.getUsername() != null && dpService.getPassword() != null){
					String authString = dpService.getUsername() + ":" + dpService.getPassword();
					byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
					String authStringEnc = new String(authEncBytes);
					httpConn.setRequestProperty("Authorization", "Basic " + authStringEnc);
				}
				
				httpConn.setRequestMethod( dpService.getHttpMethod());
				httpConn.setDoOutput(true);
				httpConn.setDoInput(true);
				// Everything's set up; send the XML that was read in to b.
				OutputStream out = httpConn.getOutputStream();
				out.write(b);    
				out.close();
				if (httpConn.getResponseCode() == 200) { 
					InputStreamReader isr =	new InputStreamReader(httpConn.getInputStream());
					BufferedReader in = new BufferedReader(isr);

					String inputLine;
					
					while ((inputLine = in.readLine()) != null){
						output = output+inputLine;
					}

					in.close();
				}else{
					output="Return Code:"+httpConn.getResponseCode();
				}
				// Read the response and write it to standard out.
				
				return output;

				
				
				//httpConn.setRequestProperty("Authorization","Basic Z295YWxyYWRtaW46VHJhbnNmZXIxMiM=");
				
			}else{
				logger.error("HttpURLConnection connection obj is null");
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			
			logger.error(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
			logger.error(e);
		}
		
		
		return output;
		
	}

}
